import Vue from 'vue'
import Router from 'vue-router'
import Home from '../components/Home'
import Login from '../components/user/Login'
import Register from '../components/user/Register'
import UserUpdate from '../components/user/UserUpdate'
import Commodity from '../components/commodity/Commodity'
import Single from '../components/commodity/single/Single'
import Cart from '../components/user/Cart'
import Order from '../components/order/Order'
import OrderUpdate from '../components/order/OrderUpdate'
import Pay from '../components/pay/Pay'

import Index from '../components/Index'
Vue.use(Router);

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};

const router = new Router({
  routes: [
    {
      path: '/',
      redirect:'/index',
    },
    {
      path: '/index',
      name: 'Index',
      component: Index,
      redirect:'/index/home',
      children:[
        {
          path: 'home',
          name: 'Home',
          component: Home
        },
        {
          path: '/commodity',
          name: 'Commodity',
          component: Commodity
        },
        {
          path: '/commodity/single/:id',
          name: 'Single',
          component: Single
        },
        {
          path: '/order',
          name: 'Order',
          component: Order
        },
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/register',
      name: 'Register',
      component: Register
    },
    {
      path: '/userUpdate',
      name: 'UserUpdate',
      component: UserUpdate
    },


    {
      path: '/cart',
      name: 'Cart',
      component: Cart
    },

    {
      path: '/orderUpdate/:id',
      name: 'OrderUpdate',
      component: OrderUpdate
    },
    {
      path: '/pay',
      name: 'Pay',
      component: Pay
    },

  ]
})

// 挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作 next('/login')强制跳转login
/*router.beforeEach((to, from, next) => {
  // 访问登录页，放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('user')
  // 没有token, 强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})*/
router.beforeEach((to, from, next) => {
  // 访问登录页，放行
  if (to.path === '/login'){
    sessionStorage.setItem('prePath',from.path);
    return next();
  }else {
    return next()
  }
})

export default router
